import { intl } from '@/utils';
import { Spin } from 'antd';
import { TextBox } from 'devextreme-react';
import { Item } from 'devextreme-react/toolbar';
import { throttle } from 'lodash';
import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';
import { useModel } from 'umi';
import { CpasIcon, DevGrid, DevToolBar, DevTree, LayoutB } from '~/public/cpas-ui';
import { getSubjectInvList } from '../../service';

const InvGrid = React.forwardRef((props: any, ref) => {
  const { initialState } = useModel('@@initialState');
  const { projectCode = '', dbname = '' } = initialState?.curPart || {};
  const [spinLoad, setSpinLoad] = useState<boolean>(false);

  const {
    AccountDataID,
    AccountTreeList,
    statisticType,
    columnsData,
    timeData,
    startAndEndYear,
  } = props;

  const [categoryId, setCategoryId] = useState('all');
  // 触发局部组件刷新
  const [refreshTime, setRefreshTime] = useState(new Date().getTime());

  const DataRef = useRef<any>();
  const devTreeRef = useRef<any>();

  // 分页
  const [totalCount, setTotalCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(50);
  const [devGuidData, setDevGuidData] = useState<any[]>([]);

  const getDevGridData = async (params: any) => {
    if (spinLoad) return;
    setSpinLoad(true);
    try {
      const res = await getSubjectInvList(params);
      if (res.success) {
        setDevGuidData(res.data);
      }
      setSpinLoad(false);
    } catch (error) {
      setSpinLoad(false);
    } finally {
      setSpinLoad(false);
    }
  };

  useEffect(() => {
    if (AccountDataID && statisticType) {
      const { startYear, endYear } = startAndEndYear;
      const params = {
        dbname,
        Data_ID: AccountDataID,
        statisticType,
        categoryId: categoryId || 'all', // 默认选择全部
        startYear,
        endYear,
      };
      getDevGridData(params);
    }
  }, [AccountDataID, statisticType, categoryId, refreshTime, timeData, startAndEndYear]);
  // 自定义方法
  useImperativeHandle(ref, () => ({
    reloadDevTable: () => {},
    resetInvGrid: () => {
      setDevGuidData([]);
      setCategoryId('0');
    },
  }));

  const inputSearch = (content: any) => {
    DataRef.current.instance.searchByText(content || '');
  };
  const throttleSearch = throttle(inputSearch, 100);
  const getInputValue = (e: any) => {
    const { event } = e;
    throttleSearch(event.target.value);
  };

  const selectItem = useCallback((e: any) => {
    const itemData = e.itemData;
    setCategoryId(itemData.id);
  }, []);

  const leftContainer = useMemo(() => {
    return (
      <div style={{ margin: '8px', height: '100%' }}>
        <DevTree.Default
          id="treeViewTest"
          ref={devTreeRef}
          selectByClick={true}
          selectionMode="single"
          items={AccountTreeList}
          dataStructure="plain"
          searchMode="contains"
          displayExpr="name"
          parentIdExpr="pid"
          keyExpr="id"
          rootValue="null"
          onItemClick={selectItem}
        />
      </div>
    );
  }, [AccountTreeList]);

  const rightContainer = useMemo(() => {
    return (
      <div
        style={{ width: '100%', height: '100%', marginBottom: '10px', padding: '8px 0px 8px 16px' }}
      >
        <DevToolBar.Default style={{ height: '36px', marginBottom: '8px' }}>
          <Item location="after">
            <TextBox
              width={200}
              style={{ paddingRight: '8px' }}
              onInput={(e: any) => getInputValue(e)}
              className="TextBoxButtons_Style"
              buttons={[
                {
                  location: 'before',
                  name: 'search',
                  options: {
                    icon: 'iconfont icon-search',
                    disabled: true,
                  },
                },
              ]}
            />{' '}
            {/*  */}
          </Item>
          <Item location="after">
            <div className="IconRefresh_Style">
              <CpasIcon
                type="icon-refresh"
                fontSize={16}
                onClick={() => {
                  setRefreshTime(new Date().getTime());
                }}
              />
            </div>
          </Item>
        </DevToolBar.Default>
        {spinLoad && (
          <div
            style={{
              position: 'relative',
              height: 'calc(100% - 50px)',
              width: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-around',
            }}
          >
            <Spin spinning={spinLoad}></Spin>
          </div>
        )}

        <DevGrid.Default
          id="ageTableId"
          width="100%"
          height={'calc(100% - 50px)'}
          dataSource={devGuidData}
          // rowAlternationEnabled={true}
          ref={DataRef}
          keyExpr="GUID"
          disableFirstHeaderSearch={true}
          className="devHeadersCenter PaperDevSortableGrid "
          columns={columnsData}
          columnResizingMode="widget"
          columnMinWidth={20}
          allowColumnResizing={true}
          scrolling={
            {
              // rowRenderingMode: 'virtual',
              // columnRenderingMode: 'virtual',
              // mode: 'virtual',
              // mode: 'infinite',
            }
          }
          showBorders={true}
          showRowLines={true}
          showColumnLines={true}
          paging={{
            enabled: true,
          }}
          headerFilter={{
            visible: true,
            allowSearch: true,
            width: 300,
            texts: { ok: intl('pub.ok', '确定') },
          }}
          filterPanel={{ visible: false }}
          filterRow={{ visible: false }}
        ></DevGrid.Default>

        {/* <div style={{ width: '100%', marginTop: '10px' }}>
              <Pagination
                defaultCurrent={50}
                pageSize={pageSize}
                current={currentPage}
                total={totalCount}
                showTotal={(total) => {
                  return `${intl('auditPaperTable.title.Total', '共')} ${total} ${intl(
                    'auditPaperTable.title.items',
                    '条',
                  )}`;
                }}
                onChange={handlePageChange}
                onShowSizeChange={handlePageSizeChange}
              />
            </div> */}
      </div>
    );
  }, [devGuidData, columnsData, spinLoad, currentPage, pageSize, totalCount]);

  return (
    <>
      <LayoutB
        rowSize={['20%', '20px', '82%']}
        leftSlot={leftContainer}
        rightSlot={rightContainer}
      />
    </>
  );
});
export default InvGrid;
